﻿using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace CloudClipboardSync.Converters
{
    class SwitchConverter: MarkupExtension, IValueConverter
    {
        public object If { get; set; }
        public object Then { get; set; }
        public object Else { get; set; }

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var b = AcceptableValue(If, value);
            return b ? Then : Else;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }

        #endregion

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }

        public static bool StringEquals(object objA, object objB)
        {
            return Equals(objA, objB) || Equals((objA ?? "null").ToString().ToLower(), (objB ?? "null").ToString().ToLower());
        }

        private static string SameStringRepresentation(object obj)
        {
            return obj.ToString().Trim().ToLower();
        }

        public static bool AcceptableValue(object descriptor, object value)
        {
            var descStr = SameStringRepresentation(descriptor);
            var valueStr = SameStringRepresentation(value);
            return Equals(descStr, valueStr) || descStr.Split(',').Select(x => x.Trim()).Any(x => x == valueStr);
        }
    }
}
